<template>
    <div class="menu-management">
        <!-- 标题区域 -->
        <div class="box">
            <div class="size-24">项目管理</div>
        </div>

        <!-- 搜索区域 -->
        <div class="search-bar">
            <div class="search-group flex gap-4 items-center">
                <el-input v-model="name_serch" clearable style="width: 250px" placeholder="请输入项目名称"
                    :suffix-icon="Search" />
            </div>
            <!-- 新增/回收站/编辑按钮 -->
            <div>
                <el-button type="danger" @click="openRecycleDialog">回收站</el-button>
                <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
        </div>

        <!-- 项目管理表格：渲染分页后的数据 tableData -->
        <el-table :data="tableData" stripe style="width: 100%" border>
            <el-table-column prop="id" label="序号" width="80" align="center" />
            <el-table-column prop="title" label="项目名称" align="center" />
            <el-table-column prop="student" label="公司标识" align="center" />
            <el-table-column prop="account" label="公司名称" align="center" />
            <el-table-column prop="address" label="项目地址" align="center" />
            <el-table-column prop="start_time" label="开始时间" align="center" />
            <el-table-column prop="end_time" label="结束时间" align="center" />
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDel(scope.row)">下架</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 项目管理分页 -->
        <div class="demo-pagination-block">
            <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                :page-sizes="[5, 10, 20, 100]" :size="size" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="pagetotle" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 新增/编辑项目弹窗 -->
        <el-dialog :title="dialogTitle" v-model="isDialogVisible" width="70%" :before-close="handleClose">
            <el-form ref="projectFormRef" :model="projectForm" :rules="projectRules" label-width="120px">
                <!-- 项目所属公司：渲染 getOrgTree 的 account 和 id -->
                <el-form-item label="项目所属公司" prop="company">
                    <el-select v-model="projectForm.company" placeholder="请选择项目所属公司">
                        <el-option v-for="item in companyList" :key="item.id" :label="item.account" :value="item.id" />
                    </el-select>
                </el-form-item>

                <!-- 项目名称 -->
                <el-form-item label="项目名称" prop="title">
                    <el-input v-model="projectForm.title" placeholder="请输入项目名称,例:人力资源项目-A" />
                </el-form-item>

                <!-- 项目地址 -->
                <el-form-item label="项目地址" prop="address">
                    <el-input v-model="projectForm.address" placeholder="请输入项目地址" />
                </el-form-item>

                <!-- 项目周期 -->
                <el-form-item label="项目周期" prop="period">
                    <el-date-picker v-model="projectForm.start_time" type="date" placeholder="开始时间" :size="size" />
                    <span style="margin: 0 10px;">-</span>
                    <el-date-picker v-model="projectForm.end_time" type="date" placeholder="结束时间" :size="size" />
                </el-form-item>

                <!-- 操作员账号 + 操作员密码 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="操作员账号" prop="czaccount">
                            <el-input v-model="projectForm.czaccount" placeholder="请输入操作员账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="操作员密码" prop="operatorPassword">
                            <el-input v-model="projectForm.operatorPassword" type="password" placeholder="请输入操作员密码" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 项目会计账号 + 项目会计密码 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="项目会计账号" prop="kjaccount">
                            <el-input v-model="projectForm.kjaccount" placeholder="请输入项目会计账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目会计密码" prop="accountantPassword">
                            <el-input v-model="projectForm.accountantPassword" type="password"
                                placeholder="请输入项目会计密码" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 项目经理账号 + 项目经理密码 -->
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="项目经理账号" prop="jlaccount">
                            <el-input v-model="projectForm.jlaccount" placeholder="请输入项目经理账号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目经理密码" prop="managerPassword">
                            <el-input v-model="projectForm.managerPassword" type="password" placeholder="请输入项目经理密码" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 个人社保基数 -->
                <el-form-item label="个人社保基数" prop="gr_security">
                    <el-input v-model.number="projectForm.gr_security" type="number" placeholder="请输入个人社保基数" />
                </el-form-item>

                <!-- 单位社保基数 -->
                <el-form-item label="单位社保基数" prop="dw_security">
                    <el-input v-model.number="projectForm.dw_security" type="number" placeholder="请输入单位社保基数" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="resetFormAndClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 项目回收站弹窗 -->
        <el-dialog title="项目回收站" v-model="isRecycleDialogVisible" width="80%" :before-close="handleRecycleClose">
            <!-- 回收站搜索区域 -->
            <div class="search-bar mb-4">
                <el-input v-model="recycleSearchName" clearable placeholder="请输入项目名称" style="width: 250px" @change="fetchRecycleData"/>
            </div>

            <!-- 回收站表格 -->
            <el-table :data="recycleFilteredData" stripe style="width: 100%" border>
                <el-table-column prop="id" label="序号" width="80" align="center" />
                <el-table-column prop="title" label="项目名称" align="center" />
                <el-table-column prop="student" label="公司标识" align="center" />
                <el-table-column prop="account" label="公司名称" align="center" />
                <el-table-column prop="address" label="项目地址" align="center" />
                <el-table-column prop="start_time" label="开始时间" align="center" />
                <el-table-column prop="end_time" label="结束时间" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleRecover(scope.row)">恢复</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 回收站分页 -->
            <div class="demo-pagination-block mt-4">
                <el-pagination v-model:current-page="recycleCurrentPage" v-model:page-size="recyclePageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="recycleTotal" @size-change="handleRecycleSizeChange"
                    @current-change="handleRecycleCurrentChange" />
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive } from 'vue';
import { Search } from '@element-plus/icons-vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { dayjs } from 'element-plus';
// 假设接口请求方法，需根据实际项目替换（若接口路径不同，需对应修改）
import {
    itemList,
    itemAdd,
    itemEdit,
    getOrgTree,
    itemDel,
    itemBack, // 项目恢复接口
} from '/@/api/item/items';

// 项目管理数据分层
const allTableData = ref<any[]>([]); // 全部原始项目数据
const filteredData = ref<any[]>([]); // 搜索过滤后的数据
const tableData = ref<any[]>([]); // 表格当前页数据

// 项目管理分页配置
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const size = ref<ComponentSize>('default');
const background = ref(true);
const pagetotle = ref<number>(0);

// 项目管理搜索关键字
const name_serch = ref('');
// 公司列表（存储 getOrgTree 数据）
const companyList = ref<any[]>([]);

// 新增/编辑弹窗相关
const isDialogVisible = ref(false);
const dialogTitle = ref('新增项目');
const isEditMode = ref(false);
const currentEditId = ref('');
const projectFormRef = ref<FormInstance>();

// 表单数据
const projectForm = reactive({
    company: '',
    title: '',
    address: '',
    start_time: '', // 开始时间
    end_time: '', // 结束时间
    czaccount: '',
    operatorPassword: '',
    kjaccount: '',
    accountantPassword: '',
    jlaccount: '',
    managerPassword: '',
    gr_security: 0,
    dw_security: 0,
});

// 表单校验规则
const projectRules = reactive<FormRules>({
    company: [{ required: true, message: '请选择项目所属公司', trigger: 'change' }],
    title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
    address: [{ required: true, message: '请输入项目地址', trigger: 'blur' }],
    start_time: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    end_time: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    czaccount: [{ required: true, message: '请输入操作员账号', trigger: 'blur' }],
    operatorPassword: [{ required: true, message: '请输入操作员密码', trigger: 'blur' }],
    kjaccount: [{ required: true, message: '请输入项目会计账号', trigger: 'blur' }],
    accountantPassword: [{ required: true, message: '请输入项目会计密码', trigger: 'blur' }],
    jlaccount: [{ required: true, message: '请输入项目经理账号', trigger: 'blur' }],
    managerPassword: [{ required: true, message: '请输入项目经理密码', trigger: 'blur' }],
    gr_security: [{ required: true, message: '请输入个人社保基数', trigger: 'blur' }],
    dw_security: [{ required: true, message: '请输入单位社保基数', trigger: 'blur' }],
});

// 回收站相关
const isRecycleDialogVisible = ref(false); // 回收站弹窗显示控制
const recycleTableData = ref<any[]>([]); // 回收站表格原始数据
const recycleFilteredData = ref<any[]>([]); // 回收站搜索过滤后的数据
const recycleCurrentPage = ref(1); // 回收站当前页码
const recyclePageSize = ref(10); // 回收站每页条数
const recycleTotal = ref<number>(0); // 回收站数据总数
const recycleSearchName = ref(''); // 回收站搜索关键字

// 页面挂载：初始化项目管理数据
onMounted(() => {
    fetchAllData();
});

// 获取项目管理数据
const fetchAllData = async () => {
    // 获取项目列表
    try {
        const res = await itemList({ projectid: '', status: 0 });
        allTableData.value = res.data || [];
        filterAndPaginateData();
    } catch (error) {
        console.error('获取项目数据失败:', error);
        allTableData.value = [];
        filteredData.value = [];
        tableData.value = [];
        pagetotle.value = 0;
    }

    // 获取公司列表（getOrgTree）
    try {
        const respon = await getOrgTree({ userid: '' });
        companyList.value = respon.data || [];
    } catch (error) {
        console.error('获取公司数据失败:', error);
        companyList.value = [];
    }
};

// 项目管理数据过滤 + 分页
const filterAndPaginateData = () => {
    const searchTerm = name_serch.value.toLowerCase().trim();
    if (!searchTerm) {
        filteredData.value = [...allTableData.value];
    } else {
        filteredData.value = allTableData.value.filter((item) =>
            item.title?.toLowerCase().includes(searchTerm)
        );
    }
    pagetotle.value = filteredData.value.length;
    const startIndex = (currentPage4.value - 1) * pageSize4.value;
    const endIndex = startIndex + pageSize4.value;
    tableData.value = filteredData.value.slice(startIndex, endIndex);
};

// 项目管理分页：切换每页条数
const handleSizeChange = (val: number) => {
    pageSize4.value = val;
    currentPage4.value = 1;
    filterAndPaginateData();
};

// 项目管理分页：切换页码
const handleCurrentChange = (val: number) => {
    currentPage4.value = val;
    filterAndPaginateData();
};

// 项目管理搜索监听
watch(name_serch, () => {
    currentPage4.value = 1;
    filterAndPaginateData();
}, { immediate: false });

// 新增项目弹窗显示
const handleAdd = () => {
    isDialogVisible.value = true;
    isEditMode.value = false;
    dialogTitle.value = '新增项目';
    projectFormRef.value?.resetFields();
};

// 编辑项目弹窗显示及数据回显
const handleEdit = async (row: any) => {
    isDialogVisible.value = true;
    isEditMode.value = true;
    dialogTitle.value = '编辑项目';
    currentEditId.value = row.id;

    try {
        const res = await itemEdit({ id: row.id });
        const itemData = res.data;
        const accountData = res.account;

        // 项目基础信息回显
        projectForm.company = itemData.companyid || '';
        projectForm.title = itemData.title || '';
        projectForm.address = itemData.address || '';
        projectForm.start_time = itemData.start_time || '';
        projectForm.end_time = itemData.end_time || '';
        projectForm.gr_security = itemData.gr_security || 0;
        projectForm.dw_security = itemData.dw_security || 0;

        // 账号信息回显
        const laborAccount = accountData.find((item: any) => item.account.includes('劳资员'));
        const accountantAccount = accountData.find((item: any) => item.account.includes('会计'));
        const managerAccount = accountData.find((item: any) => item.account.includes('项目经理'));

        projectForm.czaccount = laborAccount ? laborAccount.account : '';
        projectForm.kjaccount = accountantAccount ? accountantAccount.account : '';
        projectForm.jlaccount = managerAccount ? managerAccount.account : '';
    } catch (error) {
        console.error('获取编辑数据失败:', error);
        ElMessage.error('获取编辑数据失败');
        isDialogVisible.value = false;
    }
};

// 提交表单（新增/编辑项目）
const handleSubmit = async () => {
    await projectFormRef.value?.validate();
    try {
        // 格式化开始时间和结束时间
        const formattedStartTime = dayjs(projectForm.start_time).format('YYYY-MM-DD HH:mm:ss');
        const formattedEndTime = dayjs(projectForm.end_time).format('YYYY-MM-DD HH:mm:ss');

        const requestData = {
            companyid: projectForm.company,
            title: projectForm.title,
            address: projectForm.address,
            start_time: formattedStartTime,
            end_time: formattedEndTime,
            gr_security: projectForm.gr_security,
            dw_security: projectForm.dw_security,
            id: isEditMode.value ? [currentEditId.value] : [],
            account: [projectForm.czaccount, projectForm.kjaccount, projectForm.jlaccount],
            password: [
                projectForm.operatorPassword,
                projectForm.accountantPassword,
                projectForm.managerPassword,
            ],
            project_type: [3, 2, 1],
        };

        if (isEditMode.value) {
            await itemEdit(requestData);
            ElMessage.success('编辑项目成功');
        } else {
            await itemAdd(requestData);
            ElMessage.success('新增项目成功');
        }
        isDialogVisible.value = false;
        fetchAllData(); // 重新获取项目列表，更新表格
    } catch (error) {
        ElMessage.error(isEditMode.value ? '编辑项目失败' : '新增项目失败');
        console.error('操作失败:', error);
    }
};

// 弹窗关闭回调（新增/编辑弹窗）
const handleClose = (done: () => void) => {
    projectFormRef.value?.resetFields();
    isEditMode.value = false;
    done();
};

// 重置表单并关闭弹窗（新增/编辑弹窗）
const resetFormAndClose = () => {
    projectFormRef.value?.resetFields();
    isDialogVisible.value = false;
    isEditMode.value = false;
};

// 下架项目
const handleDel = async (row: any) => {
    try {
        await itemDel({ id: row.id });
        ElMessage.success('项目下架成功');
        fetchAllData(); // 重新获取项目列表，更新表格
    } catch (error) {
        ElMessage.error('项目下架失败');
        console.error('下架失败:', error);
    }
};

// 打开回收站弹窗并加载数据
const openRecycleDialog = async () => {
    isRecycleDialogVisible.value = true;
    await fetchRecycleData();
};

// 获取回收站项目数据
const fetchRecycleData = async () => {
  try {
    const res = await itemList({ projectid: '', status: 1 })
    recycleTableData.value = res.data || [];
    filterAndPaginateRecycleData(); // 新增调用，确保搜索后分页正确
  } catch (error) {
    console.error('获取回收站数据失败:', error);
    recycleTableData.value = [];
    recycleFilteredData.value = [];
    recycleTotal.value = 0;
  }
};

// 回收站数据过滤 + 分页
const filterAndPaginateRecycleData = () => {
  const searchTerm = recycleSearchName.value.toLowerCase().trim();
  let filtered = [...recycleTableData.value];
  // 搜索过滤
  if (searchTerm) {
    filtered = filtered.filter((item) =>
      item.title?.toLowerCase().includes(searchTerm)
    );
  }
  recycleTotal.value = filtered.length;
  // 分页切片
  const startIndex = (recycleCurrentPage.value - 1) * recyclePageSize.value;
  const endIndex = startIndex + recyclePageSize.value;
  recycleFilteredData.value = filtered.slice(startIndex, endIndex);
};

// 回收站分页：切换每页条数
const handleRecycleSizeChange = (val: number) => {
  recyclePageSize.value = val;
  recycleCurrentPage.value = 1;
  filterAndPaginateRecycleData();
};

// 回收站分页：切换页码
const handleRecycleCurrentChange = (val: number) => {
  recycleCurrentPage.value = val;
  filterAndPaginateRecycleData();
};

// 回收站弹窗关闭回调
const handleRecycleClose = (done: () => void) => {
    recycleSearchName.value = '';
    done();
};

// 恢复回收站项目
const handleRecover = async (row: any) => {
    try {
        await itemBack({ id: row.id });
        ElMessage.success('项目恢复成功');
        await fetchRecycleData(); // 重新加载回收站数据
        fetchAllData(); // 重新加载项目管理列表数据
    } catch (error) {
        ElMessage.error('项目恢复失败');
        console.error('恢复失败:', error);
    }
};
</script>

<style scoped>
.menu-management {
    padding: 20px;
}

.box {
    padding-left: 10px;
}

.size-24 {
    font-size: 24px;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 20px;
}

.search-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.flex {
    display: flex;
}

.gap-4 {
    gap: 16px;
}

.demo-pagination-block {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.el-button--small {
    --el-button-size: 35px;
    height: var(--el-button-size);
}

.el-row {
    margin-bottom: 22px;
}
</style>